package com.evl.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.evl.utils.filter.Filter;
import com.evl.utils.filter.ListFilter;

/*
 * 对象操作工具类
 */
public class ObjectUtil { 

	/**
	 * 映射e对象的值到对应的o对象并返回
	 * @param o
	 * @param e
	 * @return
	 */
	public static <T,E> T concat(T o,E e){
		Field[] fields = o.getClass().getDeclaredFields();
		for(Field field : fields){
			String fiedlName = field.getName();
			try {
				Method me = e.getClass().getMethod("get"+toGetMethodName(fiedlName));
				if(null == me){
					continue;
				}
				Object value = me.invoke(e);
				Class<?> clazz  = field.getType();
				Method mo = o.getClass().getMethod("set"+toGetMethodName(fiedlName),clazz);
				mo.invoke(o, value);
			}catch (Exception e1) {
				continue;
			}
		}
		return o;
	}
	
	/**
	 * 将List<Object>转换成List<Map>,通过过滤器过滤，不需要过滤过滤器为null
	 * @param list
	 * @param filter
	 * @return
	 */
	public static <T> List toListMap(List<T> list,Filter filter){
		List<Map> rest = new ArrayList<Map>();
		if(list != null && list.size() > 0){
			for(Object o : list){
				boolean isRemove = filter.isRemove(o);
				if(!isRemove){
					Map m = toMap(o,filter);
					rest.add(m);
				}
			}
		}
		return rest;
	}
	
	/**
	 * 将Object转换成Map,通过过滤器过滤，不需要过滤过滤器为null
	 * @param list
	 * @param filter
	 * @return
	 */
	public static Map<String,Object> toMap(Object o,Filter filter){
		Map<String,Object> map = new HashMap<String,Object>();
		Field[] fields = o.getClass().getDeclaredFields();
		for(Field field : fields){
			String fiedlName = field.getName();
			try {
				Method me = o.getClass().getMethod("get"+toGetMethodName(fiedlName));
				if(null == me){
					continue;
				}
				Object value = me.invoke(o);
				if(filter != null){
					value = filter.filtration(fiedlName, value);
				}
				map.put(fiedlName, value);
			}catch (Exception e) {
				continue;
			}
		}
		return map;
	}
	
	public static String toGetMethodName(String name){
		String firstChar = name.substring(0,1);
		return firstChar.toUpperCase()+name.substring(1);
	}

	/**
	 * list对象过滤
	 * @param list
	 * @param filter
	 * @return
	 */
	public static <T> List<T> filterList(List<T> list,ListFilter<T> filter){
		List<T> resout;
		try {
			resout = list.getClass().newInstance();  //使用传入的list对象类型
		} catch (Exception e) {
			e.printStackTrace();
			resout = new ArrayList<T>();		//异常时使用arraylist
		}
		for(T l:list){
			if(!filter.isRemove(l)){
				resout.add(filter.filterElement(l));
			}
		}
		return resout;
	}
	
}
